<template>
  <div class="channeList-wrap" ref="listRef">
    <van-pull-refresh
      v-model="refreshLoading"
      :success-text="successText"
      success-duration="1500"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
      <!-- 列表项 -->
       <ArticleItem v-for="(articleValue, index) in list"
          :key="index" :articleValue="articleValue"/>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import {debounce} from 'lodash'
import ArticleItem from '@/components/article-item'
import { getArticles } from '@/api/user.js'
export default {
  name: 'ChannelList',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      nextPage: null, // 下一页时间戳
      refreshLoading: false, // 下拉刷新的loading
      successText: '', // 下来刷新啊成功的提示
      scrollTop:''//滚动条距离顶端的距离
    }
  },
  props: {
    listData: {
      type: Object,
      require: true
    }
  },
  components: {
    ArticleItem
  },
  //缓存中激活触发
  activated(){
          this.$refs.listRef.scrollTop = this.scrollTop//当组件再次调用的时候，将滚动条的位置进行赋值
  },
  deactivated(){
      // console.log('离开缓存调用')
  },
  mounted(){
     let result = this.$refs.listRef
     result.onscroll = debounce(()=>{
           this.scrollTop = result.scrollTop
     },50) 
    //  debounce(function(){},50)
  },
  methods: {
    async onLoad () {
      try {
        // 1、请求获取数据
        const params = {
          channel_id: this.listData.id, // 频道的id
          timestamp: this.nextPage || Date.now(), // 时间戳
          with_top: 1
        }
        const { data } = await getArticles(params)
        // 2 把数据放到list 数组中；注意，是push进去 (下面使用点点的方式实现数组合并)
        this.list.push(...data.data.results)
        // 3 加载状态结束
        this.loading = false
        // 数据全部加载完成
        //  this.nextPage = data.data.pre_timestamp
        // this.finished = true;
        if (data.data.results.length) {
          // 如果有数据（不为空）
          this.nextPage = data.data.pre_timestamp
        } else {
          // 4 结束触发加载更多
          this.finished = true
        }
      } catch (error) {
        console.dir(error, 'error')
      }
    },
    // 下拉刷新
    async onRefresh () {
      try {
        // 1、请求获取数据
        const params = {
          channel_id: this.listData.id, // 频道的id
          timestamp: Date.now(), // 当前时间戳
          with_top: 1
        }
        const { data } = await getArticles(params)
        // 2.将数据放到列表中（往顶部追加）
        this.list.unshift(...data.data.results)
        // 关闭刷新状态（当你下拉的时候，会自动将refreshloading设置为true,所以，要手动将它设置为false)
        this.refreshLoading = false
        this.successText = `成功刷新了${data.data.results.length}条数据`
      } catch (error) {
        console.log(error, 'error')
      }
    }
  }
}
</script>
<style scoped lang="less">
.channeList-wrap {
  position: fixed;
  top: 90px;
  left: 0;
  right: 0;
  bottom: 50px;
  overflow-y: auto;
}
</style>
